package com.gok.seasonmovie.service;

import com.gok.seasonmovie.entity.User;
import com.gok.seasonmovie.entity.UserDTO;
import com.gok.seasonmovie.mapper.SeatMapper;
import com.gok.seasonmovie.mapper.WeChatMapper;
import com.gok.seasonmovie.util.CryptoUtil;
import com.gok.seasonmovie.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class WeChatService {

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.appsecret}")
    private String appSecret;

    @Value("${token.expiry.minutes}") // 默认过期时间
    private int tokenExpiryMinutes;

    @Autowired
    private WeChatMapper weChatMapper;

    private final JdbcTemplate jdbcTemplate;

    public WeChatService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Map<String, Object> login(String code) {
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appId, appSecret, code);
        Map<String, Object> response = HttpUtil.get(url);
        String sessionKey = (String) response.get("session_key");
        String openId = (String) response.get("openid");

        if (!StringUtils.hasText(sessionKey) || !StringUtils.hasText(openId)) {
            throw new RuntimeException("从微信中获得session_key或openid失败");
        }

        String token = UUID.randomUUID().toString();
        System.out.println("加密前token："+token);
        try {
            token = CryptoUtil.encrypt(token);
            System.out.println("加密前token："+token);
        } catch (Exception e) {
            throw new RuntimeException("Token 加密失败", e);
        }

        // 更新或插入用户记录
        String selectSql = "SELECT COUNT(*) FROM user WHERE openid = ?";
        Integer count = jdbcTemplate.queryForObject(selectSql, new Object[]{openId}, Integer.class);

        if (count != null && count > 0) {
            String updateSql = "UPDATE user SET sessionkey = ?, time = ?, token = ? ,avatar_url = ? ,name = ? WHERE openid = ?";
            jdbcTemplate.update(updateSql, sessionKey, Instant.now(), token, "" , "", openId);
        } else {
            String insertSql = "INSERT INTO user (openid, sessionkey, time, token) VALUES (?, ?, ?, ?)";
            jdbcTemplate.update(insertSql, openId, sessionKey, Instant.now(), token);
        }


        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("code", 200);
        result.put("msg", "ok");
        return result;
    }

    public boolean isTokenExpired(String token) {
        String sql = "SELECT time FROM user WHERE token = ?";
        Date lastLoginTime = jdbcTemplate.queryForObject(sql, new Object[]{token}, Date.class);

        long now = new Date().getTime();
        long expiryTime = (lastLoginTime.getTime() + tokenExpiryMinutes * 60 * 1000);

        return now > expiryTime;
    }

    public void saveUserInfo(UserDTO userInfoDTO) {
        weChatMapper.save(userInfoDTO.getAvatarUrl(),userInfoDTO.getNickName(),userInfoDTO.getToken());
    }
}